package com.youthburin.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileOperateUtils {
	private static final Logger logger = LoggerFactory.getLogger(FileOperateUtils.class);

	public static void writeFileToOutputStream(OutputStream os, File file, int start, int end) throws IOException {
		InputStream is = null;

		try {
			byte[] b = new byte[1024 * 8];
			is = new BufferedInputStream(new FileInputStream(file));

			// 跳过已下载的文件内容
			is.skip(start);
			// I/O 读写
			for (int i, left = end - start + 1; left > 0 && ((i = is.read(b, 0, Math.min(b.length, left))) != -1); left -= i)
				os.write(b, 0, i);

			os.flush();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}

	/**
	 * 读取文件start至结束部分的内容
	 * 
	 * @param file
	 * @param start
	 *            开始位置
	 * @param end
	 *            结束位置
	 * @return
	 * @throws IOException
	 */
	public static String readFileAsString(File file, int start, int end, String charsetName) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		writeFileToOutputStream(os, file, start, end);
		return new String(os.toByteArray(), charsetName);
	}
}
